import json

from django.shortcuts import render
from django.core.cache import cache  # 引入缓存模块
from django.http import JsonResponse

# Create your views here.
from activativies.utils import query_all_dict
from teacher.models import TAct, Trelation, Teacher, TALog


def t_act_list(requst):
    """
    教工查询活动

    :param requst:
    :return:
    """

    data = []

    if cache.has_key('teacher:acts'):  # 查找是否有缓存
        data = cache.get('teacher:acts')
        if len(data) > 0:  # 如果缓存数据为空

            return JsonResponse(data, safe=False)

    datas = TAct.objects.filter(status=1).order_by('-start_time')
    data = [{
        'id': i.id,
        'name': i.name
    } for i in datas]

    if len(data) > 0:
        cache.set('teacher:acts', data, 60 * 5)

    return JsonResponse(data, safe=False)


def t_query_person(request):
    """
    教工查询联系人

    :param request:
    :return:
    """
    teacher_card = request.GET.get('card')  # 获取一卡通账号
    data = []

    if cache.has_key(f'teacher:{teacher_card}'):  # 查找是否有缓存
        data = cache.get(f'teacher:{teacher_card}')

        if len(data) > 0:
            # 缓存数据不为空
            return JsonResponse(data, safe=False)

    # 缓存为空
    teacher = Teacher.objects.get(teacher_card=teacher_card)

    data = [{
        'id': i.id,
        'name': i.name
    } for i in Trelation.objects.filter(teacher_id=teacher.id)]

    cache.set(f'teacher:{teacher_card}', data, None)  # 添加缓存
    return JsonResponse(data, safe=False)


def t_checkLog(request):
    try:
        aid = request.GET.get('aid')
        pid = request.GET.get('pid')
        p_ids = request.GET.get('person_id')  # 打卡人员的id列表[1,2,3]
        ids = json.loads(p_ids)
        for person_id in ids:
            TALog.objects.create(activity_id=aid, place_id=pid, person_id=person_id)
        return JsonResponse({'code': 1, 'msg': '打卡成功', 'count': len(ids)}, safe=False)
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '打卡错误'}, safe=False)


def get_count(request):
    query = query_all_dict('SELECT\n'
                           '	teacher_tact.`name`,\n'
                           '	COUNT(*) AS count\n'
                           'FROM\n'
                           '	teacher_talog\n'
                           '	LEFT JOIN teacher_tact ON teacher_talog.activity_id=teacher_tact.id\n'
                           'GROUP BY \n'
                           '	teacher_tact.`name`'
                           'ORDER BY `name`')
    data = [
        {
            'name': i['name'],
            'count': round(i['count'])
        }
        for i in query
    ]
    return JsonResponse(data, safe=False)


